package com.eelpo.cmmp.core.wicket.panel.grid;

import java.util.ArrayList;
import java.util.List;

import com.eelpo.cmmp.core.wicket.panel.grid.column.ColumnHeaderContainer;
import com.eelpo.cmmp.core.wicket.panel.grid.column.IColumnHeader;

import org.apache.wicket.Component;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.DataGridView;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.ISortableDataProvider;
import org.apache.wicket.markup.html.panel.Panel;

/**
 * <pre>
 * 列表控件
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class DataGrid<T> extends Panel {

	protected DataGridView<T> dataView;

	private static final long serialVersionUID = 1805170273548052732L;

	public DataGridView<T> getDataView() {
		return dataView;
	}

	public void setDataView(DataGridView<T> dataView) {
		this.dataView = dataView;
	}

	public DataGrid(String id, int pageSize, List<IColumnHeader<T>> columns, ISortableDataProvider<T> dataProvider) {
		super(id);

		setDataView(new DataGridView<T>("rows", convert(columns), dataProvider));

		getDataView().setRowsPerPage(pageSize);

		add(getDataView());

		addHeader(columns, dataProvider);
	}

	protected List<ICellPopulator<T>> convert(List<IColumnHeader<T>> columns) {

		List<ICellPopulator<T>> cellPopulators = new ArrayList<ICellPopulator<T>>(columns.size());

		for (ICellPopulator<T> column : columns) {
			cellPopulators.add(column);
		}

		return cellPopulators;
	}

	protected void addHeader(List<IColumnHeader<T>> columns, ISortableDataProvider<T> dataProvider) {

		ColumnHeaderContainer<T> headerContainer = new ColumnHeaderContainer<T>("heads");

		for (int i = 0, j = columns.size(); i < j; i++) {

			IColumnHeader<T> column = columns.get(i);

			Component component = null;

			if (column.isAllowSort()) {
				component = column.newSortHeader(headerContainer, String.valueOf(i), dataProvider);
			} else {
				component = column.newHeader(headerContainer, String.valueOf(i));
			}

			headerContainer.add(component);
			headerContainer.addColumn(column, component);
		}

		add(headerContainer);
	}

}